import React, { memo, useState, useEffect, useCallback, useMemo, useContext } from 'react';
import { message, Form } from 'antd';

import { isSuccess } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OrganizationSelect from '@/components/OrganizationSelect';

import PageRouter from '@/components/PageRouter/PageRouter';

import { salaryRecheck, queryPayrollTableToolMsg } from '@/services/salaryManage/salaryCalculate';

import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';

import SalaryConfigTipPage from '@/pages/SalaryManage/components/SalaryConfigTipPage';
import RejectTabWrapper from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/RejectTabWrapper/index';
import TabsMenuRight from '@/pages/SalaryManage/components/TabsMenuRight/index';

import { getOrganizationName } from '@/pages/SalaryManage/components/OrganizationName';

import SalaryPageProvider from './SalaryPageProvider';

const { latestSalaryYearMonth, getLastSysOperationSearchInfo } = salaryRecheck;

const defSearchInfo = {
    salaryRateKpiInd: 1,
    upAbnormalTipIndex: 5,
    contrastType: 1,
    downAbnormalTipIndex: 5
};

const defPagination = {
    // 分页
    current: 1,
    pageSize: 10
};

// 默认参数
const defaultParam = {
    organizationCode: undefined, // 行政机构编码
    period: undefined, // 年月
    organizationTreeData: undefined,
    searchModel: {
        ...defSearchInfo
    }, // 搜索
    updateSignal: false, // 更新step和
    selectedRows: [], // 选中
    pagination: {
        ...defPagination
    },
    headerLoading: false
};

const defToolMsg = {
    labelFlagIsShow: '',
    labelWhichShowFlag: '',
    tableDisplayLabel: ''
};

const getSearchInit = async (searchBol, orgCode) => {
    if (!searchBol) {
        return {};
    }
    const searchInfoRes = await getLastSysOperationSearchInfo({
        operationCode: 'salaryRecheckQueryContrast',
        organizationCode: orgCode
    });
    if (isSuccess(searchInfoRes)) {
        return searchInfoRes.data;
    }
    return defSearchInfo;
};

const SalaryPageWrapper = memo(({ type, tabProps, children, location, lastSearch, tabNameMap }) => {
    const { organizationCode: defaultOrgCode, year: defaultYear, month: defaultMonth } = location.query;

    const {
        store: { salaryShareOrgCode, salarySharePeriod },
        mergeTabStore
    } = useContext(TabStoreContext);

    const [defaultOrgEndPeriod, setDefaultOrgEndPeriod] = useState(null);

    useEffect(() => {
        if (defaultOrgCode) {
            setDefaultOrgEndPeriod({
                defOrgCode: defaultOrgCode,
                defYear: defaultYear,
                defMonth: defaultMonth
            });
            return;
        }
        if (salaryShareOrgCode) {
            setDefaultOrgEndPeriod({
                defOrgCode: salaryShareOrgCode,
                defYear: salarySharePeriod?.substr(0, 4),
                defMonth: salarySharePeriod?.substr(5)
            });
            return;
        }
        setDefaultOrgEndPeriod({});
    }, [defaultMonth, defaultOrgCode, defaultYear, salaryShareOrgCode, salarySharePeriod]);

    const [salaryProviderParam, setSalaryProviderParam] = useState(defaultParam);
    const [toolMsg, setToolMsg] = useState(defToolMsg);

    // 共享行政机构code和年月
    useEffect(() => {
        if (salaryProviderParam.organizationCode) {
            mergeTabStore({
                salaryShareOrgCode: salaryProviderParam.organizationCode,
                salarySharePeriod: salaryProviderParam.period
            });
        }
    }, [mergeTabStore, salaryProviderParam.organizationCode, salaryProviderParam.period]);

    // 改变公共数据方法
    const changeSalaryProviderParam = useCallback(
        async data => {
            const { type: changeType, ...otherProp } = data;
            // 切换行政机构
            if (changeType === 'changeOrg') {
                const [yearMonthRes, searchInfoRes] = await Promise.all([
                    latestSalaryYearMonth({
                        organizationCode: otherProp.organizationCode
                    }),
                    getSearchInit(lastSearch, otherProp.organizationCode)
                ]);

                if (!isSuccess(yearMonthRes) || !yearMonthRes.data.year || !yearMonthRes.data.month) {
                    setSalaryProviderParam({
                        ...salaryProviderParam,
                        ...otherProp,
                        selectedRows: [],
                        period: null,
                        searchModel: {
                            ...salaryProviderParam.searchModel,
                            ...searchInfoRes
                        },
                        pagination: {
                            ...salaryProviderParam.pagination,
                            current: 1
                        }
                    });
                } else {
                    const { year, month } = yearMonthRes.data;
                    setSalaryProviderParam({
                        ...salaryProviderParam,
                        ...otherProp,
                        selectedRows: [],
                        period: `${year}-${month < 10 && month.toString().length === 1 ? '0' : ''}${month}`,
                        searchModel: {
                            ...salaryProviderParam.searchModel,
                            ...searchInfoRes
                        },
                        pagination: {
                            ...salaryProviderParam.pagination,
                            current: 1
                        }
                    });
                }
            } else if (changeType === 'initPage') {
                setSalaryProviderParam({
                    ...salaryProviderParam,
                    ...otherProp,
                    selectedRows: [],
                    pagination: {
                        ...salaryProviderParam.pagination,
                        current: 1
                    }
                });
            } else if (otherProp.selectedRows) {
                setSalaryProviderParam({
                    ...salaryProviderParam,
                    ...otherProp
                });
            } else {
                setSalaryProviderParam({
                    ...salaryProviderParam,
                    ...otherProp,
                    selectedRows: []
                });
            }
        },
        [lastSearch, salaryProviderParam]
    );

    const handleOrgChange = useCallback(
        val => {
            changeSalaryProviderParam({
                type: 'changeOrg',
                organizationCode: val
            });
        },
        [changeSalaryProviderParam]
    );

    const [initialBol, setInitialBol] = useState(true);

    // 页面初始化公共数据
    useEffect(() => {
        const resetInit = async () => {
            const { defOrgCode, defYear, defMonth } = defaultOrgEndPeriod;
            const {
                organizationResponse: response,
                defaultOrganizationCode: defaultSelectCode
            } = await fetchOrganizationListAndDefault(defOrgCode);
            if (!defaultSelectCode) {
                setSalaryProviderParam({
                    ...defaultParam,
                    organizationCode: defOrgCode,
                    organizationTreeData: response,
                    period: undefined,
                    headerLoading: true
                });
                message.error(`您无【${getOrganizationName(defOrgCode)}】行政机构数据权限，若有疑问，请联系管理员！`);
                return;
            }

            if (defOrgCode === defaultSelectCode && defYear && defMonth) {
                const searchInfoRes = await getSearchInit(lastSearch, defaultSelectCode);
                setSalaryProviderParam({
                    ...defaultParam,
                    organizationCode: defaultSelectCode,
                    organizationTreeData: response,
                    period: `${defYear}-${defMonth < 10 && defMonth.toString().length === 1 ? '0' : ''}${defMonth}`,
                    headerLoading: true,
                    searchModel: {
                        ...searchInfoRes
                    }
                });
                return;
            }

            const [yearMonthRes, searchInfoRes] = await Promise.all([
                latestSalaryYearMonth({
                    organizationCode: defaultSelectCode
                }),
                getSearchInit(lastSearch, defaultSelectCode)
            ]);

            if (!isSuccess(yearMonthRes)) {
                setSalaryProviderParam({
                    ...defaultParam,
                    organizationCode: defaultSelectCode,
                    organizationTreeData: response,
                    period: undefined,
                    headerLoading: true,
                    searchModel: {
                        ...searchInfoRes
                    }
                });
                message.error(`请求【当前月份】数据失败：${yearMonthRes.msg}`);
                return;
            }
            const { year, month } = yearMonthRes.data;
            if (year && month) {
                setSalaryProviderParam({
                    ...defaultParam,
                    organizationCode: defaultSelectCode,
                    organizationTreeData: response,
                    period: `${year}-${month < 10 && month.toString().length === 1 ? '0' : ''}${month}`,
                    headerLoading: true,
                    searchModel: {
                        ...searchInfoRes
                    }
                });
            } else {
                setSalaryProviderParam({
                    ...defaultParam,
                    organizationCode: defaultSelectCode,
                    organizationTreeData: response,
                    period: null,
                    headerLoading: true,
                    searchModel: {
                        ...searchInfoRes
                    }
                });
            }
        };

        if (defaultOrgEndPeriod && initialBol) {
            setInitialBol(false);
            resetInit();
        }
    }, [defaultOrgEndPeriod, initialBol, lastSearch]);

    // tab是否显示驳回标签
    useEffect(() => {
        const organizationNowCode = salaryProviderParam.organizationCode;
        const nowPeriod = salaryProviderParam.period;
        const init = async () => {
            const year = nowPeriod.substr(0, 4);
            const month = nowPeriod.substr(5);
            const toolMsgRes = await queryPayrollTableToolMsg({
                year,
                month,
                organizationCode: organizationNowCode
            });
            if (isSuccess(toolMsgRes)) {
                setToolMsg(toolMsgRes.data);
            } else {
                setToolMsg(defToolMsg);
            }
        };
        if (tabNameMap && nowPeriod && organizationNowCode) {
            init();
        }
    }, [
        tabNameMap,
        salaryProviderParam.period,
        salaryProviderParam.organizationCode,
        salaryProviderParam.updateSignal
    ]);

    // 薪资复核tab自定义，是否显示驳回标签
    const tabNameMapView = useMemo(() => {
        if (!tabNameMap) {
            return null;
        }
        const tabMap = {};

        tabNameMap.forEach(({ name, title, tabType }) => {
            tabMap[name] = <RejectTabWrapper title={title} tabType={tabType} {...toolMsg} />;
        });

        return tabMap;
    }, [tabNameMap, toolMsg]);

    const tabBarGutter = useMemo(() => {
        const { tableDisplayLabel, labelWhichShowFlag } = toolMsg;
        return tableDisplayLabel && (labelWhichShowFlag === 1 || labelWhichShowFlag === 3) ? 90 : undefined;
    }, [toolMsg]);
    return (
        <PageHeaderWrapper type="success">
            <SalaryPageProvider.Provider
                value={{
                    ...salaryProviderParam,
                    changeSalaryProviderParam
                }}
            >
                <PageRouter
                    type={type}
                    extraButton={
                        <TabsMenuRight
                            period={salaryProviderParam.period}
                            nowPath={location.pathname}
                            organizationCode={salaryProviderParam?.organizationCode}
                            {...tabProps}
                        />
                    }
                    tabNameMapper={tabNameMap ? tabNameMapView : null}
                    tabBarGutter={tabBarGutter}
                >
                    <SalaryConfigTipPage
                        slotWrapper={
                            <Form layout="inline" style={{ position: 'absolute', top: 20, right: 0 }}>
                                <Form.Item label="行政机构" style={{ marginRight: 0 }}>
                                    <OrganizationSelect
                                        isStrictly
                                        allowClear={false}
                                        isNeedPermission
                                        style={{ width: 210 }}
                                        value={salaryProviderParam.organizationCode}
                                        onChange={handleOrgChange}
                                        dropdownMatchSelectWidth
                                        unLoading
                                    />
                                </Form.Item>
                            </Form>
                        }
                        organizationCode={salaryProviderParam?.organizationCode}
                    >
                        {children}
                    </SalaryConfigTipPage>
                </PageRouter>
            </SalaryPageProvider.Provider>
        </PageHeaderWrapper>
    );
});

export default SalaryPageWrapper;
